package cn.ibizlab.eam.core.eam_core.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.eam.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.eam.core.eam_core.domain.EMItemCS;
import cn.ibizlab.eam.core.eam_core.filter.EMItemCSSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMItemCSService;

import cn.ibizlab.eam.util.helper.CachedBeanCopier;
import cn.ibizlab.eam.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.eam.core.eam_core.mapper.EMItemCSMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[库间调整单] 服务对象接口实现
 */
@Slf4j
@Service("EMItemCSServiceImpl")
public class EMItemCSServiceImpl extends ServiceImpl<EMItemCSMapper, EMItemCS> implements IEMItemCSService {

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemRInService emitemrinService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemService emitemService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMStockService emstockService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMStorePartService emstorepartService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMStoreService emstoreService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFEmpService pfempService;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(EMItemCS et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmitemcsid()), et);
        return true;
    }

    @Override
    @Transactional
    public void createBatch(List<EMItemCS> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list, batchSize);
    }

    @Override
    @Transactional
    public boolean update(EMItemCS et) {
        fillParentData(et);
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("emitemcsid", et.getEmitemcsid()))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmitemcsid()), et);
        return true;
    }

    @Override
    @Transactional
    public void updateBatch(List<EMItemCS> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list, batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result = removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public EMItemCS get(String key) {
        EMItemCS et = getById(key);
        if(et == null){
            et = new EMItemCS();
            et.setEmitemcsid(key);
        }
        else {
        }
        return et;
    }

    @Override
    public EMItemCS getDraft(EMItemCS et) {
        fillParentData(et);
        return et;
    }

    @Override
    @Transactional
    public EMItemCS calAmount(EMItemCS et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean calAmountBatch(List<EMItemCS> etList) {
        for(EMItemCS et : etList) {
            calAmount(et);
        }
        return true;
    }

    @Override
    public boolean checkKey(EMItemCS et) {
        return (!ObjectUtils.isEmpty(et.getEmitemcsid())) && (!Objects.isNull(this.getById(et.getEmitemcsid())));
    }
    @Override
    @Transactional
    public EMItemCS confirm(EMItemCS et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean confirmBatch(List<EMItemCS> etList) {
        for(EMItemCS et : etList) {
            confirm(et);
        }
        return true;
    }

    @Override
    @Transactional
    public EMItemCS formUpdateByStockid(EMItemCS et) {
         return et ;
    }

    @Override
    @Transactional
    public boolean save(EMItemCS et) {
        if(!saveOrUpdate(et)) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(EMItemCS et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? getProxyService().update(et) : getProxyService().create(et);
        }
    }

    @Override
    @Transactional
    public boolean saveBatch(Collection<EMItemCS> list) {
        list.forEach(item->fillParentData(item));
        List<EMItemCS> create = new ArrayList<>();
        List<EMItemCS> update = new ArrayList<>();
        for (EMItemCS et : list) {
            if (ObjectUtils.isEmpty(et.getEmitemcsid()) || ObjectUtils.isEmpty(getById(et.getEmitemcsid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
        return true;
    }

    @Override
    @Transactional
    public void saveBatch(List<EMItemCS> list) {
        list.forEach(item->fillParentData(item));
        List<EMItemCS> create = new ArrayList<>();
        List<EMItemCS> update = new ArrayList<>();
        for (EMItemCS et : list) {
            if (ObjectUtils.isEmpty(et.getEmitemcsid()) || ObjectUtils.isEmpty(getById(et.getEmitemcsid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
    }

    @Override
    @Transactional
    public EMItemCS submit(EMItemCS et) {
         return et ;
    }

    @Override
    @Transactional
    public EMItemCS unConfirm(EMItemCS et) {
         return et ;
    }


	@Override
    public List<EMItemCS> selectByRid(String emitemrinid) {
        return baseMapper.selectByRid(emitemrinid);
    }
    @Override
    public void removeByRid(String emitemrinid) {
        this.remove(new QueryWrapper<EMItemCS>().eq("rid",emitemrinid));
    }

	@Override
    public List<EMItemCS> selectByItemid(String emitemid) {
        return baseMapper.selectByItemid(emitemid);
    }
    @Override
    public void removeByItemid(String emitemid) {
        this.remove(new QueryWrapper<EMItemCS>().eq("itemid",emitemid));
    }

	@Override
    public List<EMItemCS> selectByStockid(String emstockid) {
        return baseMapper.selectByStockid(emstockid);
    }
    @Override
    public void removeByStockid(String emstockid) {
        this.remove(new QueryWrapper<EMItemCS>().eq("stockid",emstockid));
    }

	@Override
    public List<EMItemCS> selectByStorepartid(String emstorepartid) {
        return baseMapper.selectByStorepartid(emstorepartid);
    }
    @Override
    public void removeByStorepartid(String emstorepartid) {
        this.remove(new QueryWrapper<EMItemCS>().eq("storepartid",emstorepartid));
    }

	@Override
    public List<EMItemCS> selectByStoreid(String emstoreid) {
        return baseMapper.selectByStoreid(emstoreid);
    }
    @Override
    public void removeByStoreid(String emstoreid) {
        this.remove(new QueryWrapper<EMItemCS>().eq("storeid",emstoreid));
    }

	@Override
    public List<EMItemCS> selectBySempid(String pfempid) {
        return baseMapper.selectBySempid(pfempid);
    }
    @Override
    public void removeBySempid(String pfempid) {
        this.remove(new QueryWrapper<EMItemCS>().eq("sempid",pfempid));
    }


    /**
     * 查询集合 已确认
     */
    @Override
    public Page<EMItemCS> searchConfirmed(EMItemCSSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMItemCS> pages=baseMapper.searchConfirmed(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMItemCS>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<EMItemCS> searchDefault(EMItemCSSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMItemCS> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMItemCS>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 草稿
     */
    @Override
    public Page<EMItemCS> searchDraft(EMItemCSSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMItemCS> pages=baseMapper.searchDraft(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMItemCS>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 待确认
     */
    @Override
    public Page<EMItemCS> searchToConfirm(EMItemCSSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMItemCS> pages=baseMapper.searchToConfirm(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMItemCS>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMItemCS et){
        //实体关系[DER1N_EMITEMCS_EMITEMRIN_RID]
        if(!ObjectUtils.isEmpty(et.getRid())){
            cn.ibizlab.eam.core.eam_core.domain.EMItemRIn r=et.getR();
            if(ObjectUtils.isEmpty(r)){
                cn.ibizlab.eam.core.eam_core.domain.EMItemRIn majorEntity=emitemrinService.get(et.getRid());
                et.setR(majorEntity);
                r=majorEntity;
            }
            et.setRname(r.getEmitemrinname());
        }
        //实体关系[DER1N_EMITEMCS_EMITEM_ITEMID]
        if(!ObjectUtils.isEmpty(et.getItemid())){
            cn.ibizlab.eam.core.eam_core.domain.EMItem item=et.getItem();
            if(ObjectUtils.isEmpty(item)){
                cn.ibizlab.eam.core.eam_core.domain.EMItem majorEntity=emitemService.get(et.getItemid());
                et.setItem(majorEntity);
                item=majorEntity;
            }
            et.setItemname(item.getIteminfo());
        }
        //实体关系[DER1N_EMITEMCS_EMSTOCK_STOCKID]
        if(!ObjectUtils.isEmpty(et.getStockid())){
            cn.ibizlab.eam.core.eam_core.domain.EMStock stock=et.getStock();
            if(ObjectUtils.isEmpty(stock)){
                cn.ibizlab.eam.core.eam_core.domain.EMStock majorEntity=emstockService.get(et.getStockid());
                et.setStock(majorEntity);
                stock=majorEntity;
            }
            et.setStockname(stock.getStockinfo());
        }
        //实体关系[DER1N_EMITEMCS_EMSTOREPART_STOREPARTID]
        if(!ObjectUtils.isEmpty(et.getStorepartid())){
            cn.ibizlab.eam.core.eam_core.domain.EMStorePart storepart=et.getStorepart();
            if(ObjectUtils.isEmpty(storepart)){
                cn.ibizlab.eam.core.eam_core.domain.EMStorePart majorEntity=emstorepartService.get(et.getStorepartid());
                et.setStorepart(majorEntity);
                storepart=majorEntity;
            }
            et.setStorepartname(storepart.getEmstorepartname());
        }
        //实体关系[DER1N_EMITEMCS_EMSTORE_STOREID]
        if(!ObjectUtils.isEmpty(et.getStoreid())){
            cn.ibizlab.eam.core.eam_core.domain.EMStore store=et.getStore();
            if(ObjectUtils.isEmpty(store)){
                cn.ibizlab.eam.core.eam_core.domain.EMStore majorEntity=emstoreService.get(et.getStoreid());
                et.setStore(majorEntity);
                store=majorEntity;
            }
            et.setStorename(store.getEmstorename());
        }
        //实体关系[DER1N_EMITEMCS_PFEMP_SEMPID]
        if(!ObjectUtils.isEmpty(et.getSempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp spfempid=et.getSpfempid();
            if(ObjectUtils.isEmpty(spfempid)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getSempid());
                et.setSpfempid(majorEntity);
                spfempid=majorEntity;
            }
            et.setSempname(spfempid.getEmpinfo());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<EMItemCS> getEmitemcsByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<EMItemCS> getEmitemcsByEntities(List<EMItemCS> entities) {
        List ids =new ArrayList();
        for(EMItemCS entity : entities){
            Serializable id=entity.getEmitemcsid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0) {
            return this.listByIds(ids);
        }
        else {
            return entities;
        }
    }


    public IEMItemCSService getProxyService() {
        return cn.ibizlab.eam.util.security.SpringContextHolder.getBean(this.getClass());
    }
}



